﻿using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;

namespace ScrumTable.UI.View.WinTouch.Win32Interopt
{
    public abstract class RasterRendererElement : FrameworkElement, IDisposable
    {
        #region P/Invoke
        [SuppressUnmanagedCodeSecurity]
        [DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]
        protected static extern void CopyMemory(IntPtr destination, IntPtr source, [MarshalAs(UnmanagedType.U4)] int length);
        #endregion

        public Image RenderedImage
        {
            get;
            private set;
        }

        protected RasterRendererElement()
        {
            RenderedImage = new Image { Stretch = Stretch.Fill };
            RenderOptions.SetBitmapScalingMode(RenderedImage, BitmapScalingMode.LowQuality);
            AddVisualChild(RenderedImage);
        }

        public abstract void RenderFrame(RenderedFrameEventArgs frameArgs);

        #region Overrides
        protected override Size MeasureOverride(Size availableSize)
        {
            RenderedImage.Measure(availableSize);
            return RenderedImage.DesiredSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            RenderedImage.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override int VisualChildrenCount
        {
            get
            {
                return 1;
            }
        }

        protected override Visual GetVisualChild(int index)
        {
            if (index > 0)
                throw new IndexOutOfRangeException();

            return RenderedImage;
        }
        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
        }

        #endregion
    }
}
